<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input v-model="listQuery.id" placeholder="学号" style="width: 120px;margin-left: 10px;" class="filter-item" @keyup.enter.native="handleFilter" />
      <el-input v-model="listQuery.name" placeholder="姓名" style="width: 120px;margin-left: 10px;" class="filter-item" @keyup.enter.native="handleFilter" />
      <el-select v-model="listQuery.tgroup" placeholder="所属小组" clearable style="width: 150px;margin-left: 10px;" class="filter-item">
        <el-option v-for="item in group" :key="item" :label="item" :value="item" />
      </el-select>
      <el-select v-model="listQuery.grade" placeholder="年级" clearable style="width: 150px;margin-left: 10px;" class="filter-item">
        <el-option v-for="item in grade" :key="item" :label="item" :value="item" />
      </el-select>
      <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" style="margin-left: 10px;" @click="handleFilter(listQuery)">
        查询
      </el-button>
      <el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-edit" @click="handleCreate">
        新增
      </el-button>
      <el-button v-waves :loading="downloadLoading" class="filter-item" type="primary" icon="el-icon-download" @click="handleDownload">
        导出名单
      </el-button>
    </div>

    <el-table
      :key="tableKey"
      v-loading="listLoading"
      :data="list"
      border
      fit
      highlight-current-row
      :default-sort="{prop: 'group', order: 'descending'}"
      style="width: 100%;"
      @sort-change="sortChange"
    >
      <!--ID字段-->
      <el-table-column label="学号" prop="id" sortable align="center" width="120" />
      <!--Name字段-->
      <el-table-column label="姓名" width="100px" align="center" prop="name" />
      <!--Phone字段-->
      <el-table-column label="电话" align="center" width="150px" prop="phone" />
      <!--tgroup字段-->
      <el-table-column label="所属小组" width="150px" align="center" sortable prop="tgroup" />
      <!--grade字段-->
      <el-table-column label="年级" sortable width="100" align="center" prop="grade" />
      <!--birthday字段-->
      <el-table-column label="生日" width="150" prop="birthday" align="center" />
      <!--qq字段-->
      <el-table-column label="QQ" align="center" width="140" prop="qq" />
      <!--creator字段-->
      <el-table-column label="创建者" class-name="status-col" width="140" prop="creator" />
      <!--updator-->
      <el-table-column label="更新者" class-name="status-col" width="140" prop="updator" />
      <!--class字段-->
      <el-table-column label="专业班级" class-name="status-col" min-width="100" prop="clas" />
      <!--操作按钮-->
      <el-table-column label="操作" align="center" width="300" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button type="primary" size="mini" @click="handleUpdate(scope.row)">
            编辑
          </el-button>
          <el-button size="mini" type="success" @click="handleModifyStatus(scope.row,'published')">
            重置密码
          </el-button>
          <el-button size="mini" type="danger" @click="handleDelete(scope.row)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="listQuery.pageNow" :limit.sync="listQuery.pageSize" @pagination="getList" />

    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form ref="dataForm" :rules="Rules" hide-required-asterisk="true" :model="temp" label-position="left" label-width="70px" style="width: 400px; margin-left:50px;">
        <!--输入学号-->
        <el-form-item label="学号" prop="id">
          <el-input v-model="temp.id" />
        </el-form-item>
        <!--输入姓名-->
        <el-form-item label="姓名" prop="name">
          <el-input v-model="temp.name" />
        </el-form-item>
        <!--输入电话-->
        <el-form-item label="电话" prop="phone">
          <el-input v-model="temp.phone" type="phone" />
        </el-form-item>
        <!--输入小组-->
        <el-form-item label="小组" prop="tgroup">
          <el-select v-model="temp.tgroup" class="filter-item" placeholder="Please select">
            <el-option v-for="item in group" :key="item" :label="item" :value="item" />
          </el-select>
        </el-form-item>
        <!--输入小组-->
        <el-form-item label="年级" prop="grade">
          <el-input v-model="temp.grade" />
        </el-form-item>
        <!--输入生日-->
        <el-form-item label="生日" prop="birthday">
          <el-date-picker v-model="temp.birthday" type="date" placeholder="Please pick a date" />
        </el-form-item>
        <!--输入qq-->
        <el-form-item label="qq" prop="qq">
          <el-input v-model="temp.qq" />
        </el-form-item>
        <!--输入qq-->
        <el-form-item label="专业班级" prop="clas">
          <el-input v-model="temp.clas" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          取消
        </el-button>
        <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">
          确认
        </el-button>
      </div>
    </el-dialog>

    <el-dialog :visible.sync="dialogPvVisible" title="Reading statistics">
      <el-table :data="pvData" border fit highlight-current-row style="width: 100%">
        <el-table-column prop="key" label="Channel" />
        <el-table-column prop="pv" label="Pv" />
      </el-table>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="dialogPvVisible = false">Confirm</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { fetchList, fetchPv, createArticle } from '@/api/article'
import waves from '@/directive/waves' // waves directive
import { parseTime } from '@/utils'
import Pagination from '@/components/Pagination'
import { addUser, deleteUser, getList, resetPassword, updateArticle } from '@/api/user' // secondary package based on el-pagination

const calendarTypeOptions = [
  { key: 'CN', display_name: 'China' },
  { key: 'US', display_name: 'USA' },
  { key: 'JP', display_name: 'Japan' },
  { key: 'EU', display_name: 'Eurozone' }
]

// arr to obj, such as { CN : "China", US : "USA" }
const calendarTypeKeyValue = calendarTypeOptions.reduce((acc, cur) => {
  acc[cur.key] = cur.display_name
  return acc
}, {})

export default {
  name: 'BasicInfo',
  components: { Pagination },
  directives: { waves },
  filters: {
    statusFilter(status) {
      const statusMap = {
        published: 'success',
        draft: 'info',
        deleted: 'danger'
      }
      return statusMap[status]
    },
    typeFilter(type) {
      return calendarTypeKeyValue[type]
    }
  },
  data() {
    //  姓名的规则
    const validateInput1 = (rule, value, callback) => {
      var reg = /\d/
      if (reg.test(value)) {
        callback(new Error('名字不能是数字'))
      } else if (!value) {
        callback(new Error('不能为空'))
      } else {
        callback()
      }
    }
    // id的规则
    const validateInput2 = (rule, value, callback) => {
      if (isNaN(value)) {
        callback(new Error('必须是数字'))
      } else if (!value) {
        callback(new Error('不能为空'))
      } else if (value.length != 10) {
        callback(new Error('学号为10位'))
      } else {
        callback()
      }
    }
    // qq的规则
    const validateInput5 = (rule, value, callback) => {
      if (isNaN(value)) {
        callback(new Error('必须是数字'))
      } else if (!value) {
        callback(new Error('不能为空'))
      } else if (!(value.length <= 12 && value.length >= 6)) {
        callback(new Error('请输入正确长度的qq号'))
      } else {
        callback()
      }
    }
    // 电话规则
    const validateInput3 = (rule, value, callback) => {
      if (isNaN(value)) {
        callback(new Error('必须是数字'))
      } else if (!value) {
        callback(new Error('不能为空'))
      } else if (value.length != 11) {
        callback(new Error('电话号码为11位'))
      } else {
        callback()
      }
    }
    // 年级规则
    const validateInput4 = (rule, value, callback) => {
      if (isNaN(value)) {
        callback(new Error('必须是数字'))
      } else if (!value) {
        callback(new Error('不能为空'))
      } else if (value.length != 2) {
        callback(new Error('年级为2位'))
      } else {
        callback()
      }
    }
    return {
      tableKey: 0,
      // 用户信息列表
      list: null,
      // 总共有几个数据
      total: 0,
      listLoading: true,
      listQuery: {
        pageNow: 0,
        pageSize: 10,
        id: undefined,
        name: undefined,
        grade: undefined,
        tgroup: undefined
      },
      Rules: {
        id: [{ required: true, trigger: 'blur', validator: validateInput2 }],
        name: [{ required: true, trigger: 'blur', validator: validateInput1 }],
        phone: [{ required: true, trigger: 'blur', validator: validateInput3 }],
        grade: [{ required: true, trigger: 'blur', validator: validateInput4 }],
        qq: [{ required: true, trigger: 'blur', validator: validateInput5 }],
        tgroup: [{ required: true, trigger: 'blur' }],
        birthday: [{ required: true, trigger: 'blur' }],
        clas: [{ required: true, trigger: 'blur' }]
      },
      group: [],
      grade: [],
      calendarTypeOptions,
      sortOptions: [{ label: 'ID Ascending', key: '+id' }, { label: 'ID Descending', key: '-id' }],
      statusOptions: ['published', 'draft', 'deleted'],
      showReviewer: false,
      temp: {
        id: undefined,
        name: undefined,
        phone: undefined,
        tgroup: undefined,
        grade: undefined,
        birthday: undefined,
        qq: undefined,
        clas: undefined,
        createTime: undefined
      },
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: '编辑成员信息',
        create: '新增成员信息'
      },
      dialogPvVisible: false,
      pvData: [],
      rules: {
        type: [{ required: true, message: 'type is required', trigger: 'change' }],
        timestamp: [{ type: 'date', required: true, message: 'timestamp is required', trigger: 'change' }],
        title: [{ required: true, message: 'title is required', trigger: 'blur' }]
      },
      downloadLoading: false
    }
  },
  created() {
    this.getList()
  },
  methods: {
    getList() {
      this.listLoading = true
      getList(this.listQuery).then(response => {
        this.list = response.data.list
        this.total = response.data.total
        this.group = new Set()
        this.grade = new Set()
        this.list.map((re) => {
          this.group.add(re.tgroup)
          this.grade.add(re.grade)
        })
        // Just to simulate the time of the request
        setTimeout(() => {
          this.listLoading = false
        }, 1.5 * 1000)
      })
    },
    handleFilter() {
      this.listQuery.pageNow = 1
      getList(this.listQuery).then(response => {
        this.list = response.data.list
        this.total = response.data.total
        // Just to simulate the time of the request
        setTimeout(() => {
          this.listLoading = false
        }, 1.5 * 1000)
        this.reset()
      })
    },
    // 重新undefined
    reset() {
      this.listQuery.grade = undefined
      this.listQuery.id = undefined
      this.listQuery.tgroup = undefined
      this.listQuery.name = undefined
    },
    handleModifyStatus(row, status) {
      this.$confirm('此操作将重置密码, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        resetPassword(row.id).then(() => {
          this.$message({
            type: 'success',
            message: '重置成功!'
          })
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消重置'
        })
      })
    },
    sortChange(data) {
      const { prop, order } = data
      if (prop === 'id') {
        this.sortByID(order)
      }
    },
    resetTemp() {
      this.temp = {
        id: undefined,
        name: undefined,
        phone: undefined,
        tgroup: undefined,
        grade: undefined,
        birthday: undefined,
        qq: undefined,
        clas: undefined
      }
    },
    handleCreate() {
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createData() {
      console.log(this.temp.id.length)
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          addUser(this.temp).then(() => {
            this.getList()
            this.dialogFormVisible = false
            this.$notify({
              title: 'Success',
              message: 'Created Successfully',
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },
    handleUpdate(row) {
      this.temp = Object.assign({}, row) // copy obj
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const tempData = Object.assign({}, this.temp)
          tempData.timestamp = +new Date(tempData.timestamp) // change Thu Nov 30 2017 16:41:05 GMT+0800 (CST) to 1512031311464
          updateArticle(tempData).then(() => {
            const index = this.list.findIndex(v => v.id === this.temp.id)
            this.list.splice(index, 1, this.temp)
            this.dialogFormVisible = false
            this.$notify({
              title: 'Success',
              message: 'Update Successfully',
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },
    handleDelete(row) {
      deleteUser(row.id).then((res) => {
        if (res.code === 200) {
          for (let i = 0; i < this.list.length; i++) {
            if (row.id === this.list[i].id) {
              this.list.splice(i, 1)
              this.$notify({
                title: 'Success',
                message: res.message,
                type: 'success',
                duration: 2000
              })
              break
            }
          }
        }
      })
    },
    handleFetchPv(pv) {
      fetchPv(pv).then(response => {
        this.pvData = response.data.pvData
        this.dialogPvVisible = true
      })
    },
    handleDownload() {
      this.downloadLoading = true
      import('@/vendor/Export2Excel').then(excel => {
        const tHeader = ['学号', '姓名', '电话', '所属小组', '年级', '生日', 'QQ', '创建者', '更新者', '专业班级']
        const filterVal = ['id', 'name', 'phone', 'tgroup', 'grade', 'birthday', 'qq', 'creator', 'updator', '专业班级']
        const data = this.formatJson(filterVal)
        console.log(data)
        excel.export_json_to_excel({
          header: tHeader,
          data,
          filename: 'table-list'
        })
        this.downloadLoading = false
      })
    },
    formatJson(filterVal) {
      return this.list.map(v => filterVal.map(j => {
        if (j === 'birthday') {
          return parseTime(v[j])
        } else {
          return v[j]
        }
      }))
    },
    getSortClass: function(key) {
      const sort = this.listQuery.sort
      return sort === `+${key}` ? 'ascending' : 'descending'
    }
  }
}
</script>
